//
//  ZJProgressView.swift
//  mini
//
//  Created by Mac on 2017/5/19.
//  Copyright © 2017年 Mac. All rights reserved.
//

import UIKit

class ZJProgressView: UIView {
    
    
    var circelRadius:CGFloat = 0.0
    
    var bottomLayer:CAShapeLayer?
    
    var lineWidth:CGFloat = 0.0
    
    var isAnimating:Bool = false
    
    var rad:NSInteger =  0
    
    var timer:Timer?
    
    var _rate:NSInteger = 0 {
        
        didSet{
          
            if (_rate <= 0 || _rate > 100) {
                _rate = 100;
            }
            
          doViewAnimation()
            
        }
        
    }
    
    
    //配置进度白条
    var _startAngle:CGFloat = 0.0
    
    var _startRate:CGFloat = 0.0
    
    var _rWidth:CGFloat = 0.0
    
    var _shapeLayer:CAShapeLayer = {
        
        var layer:CAShapeLayer = CAShapeLayer()
        
        layer.lineWidth = 9
        
        layer.strokeColor = kWatchColor.cgColor
        
        layer.fillColor = nil
        
        return layer
        
    }()
    
    var _bPath:UIBezierPath = UIBezierPath()

    var _displayLink:CADisplayLink! //= {
        
//        let dispalyLink = CADisplayLink(target: self, selector: #selector(drawPro))
//        
//        dispalyLink.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
//        
//        dispalyLink.isPaused = true
//        
//        return dispalyLink
//    }()
    
    
    
    
    var model:ZJRunModel?{
        
        didSet{
            
            //设置初始值
            disAndCalLabel.text = model!.distance! + "m|" + model!.calories! + "卡"
            
            disAndCalLabel.textColor = kWatchColor
            
            let str:String = model!.steps! + "步"
            
            let string:NSString = str as NSString
      
            let  AttributedStr:NSMutableAttributedString = NSMutableAttributedString(string: str)
            
            AttributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 36)], range: NSMakeRange(0, string.length-1))
            
            AttributedStr.addAttributes([NSForegroundColorAttributeName:kWatchColor], range: NSMakeRange(0, string.length))
            
            stepButton.setAttributedTitle(AttributedStr, for: .normal)
            
        }
        
        
    }
    
    var disAndCalLabel:UILabel={
     
        let lab:UILabel = UILabel()
        lab.textColor = UIColor.RGBA(0/255.0, 151/255.0, 219/255.0, 1.0)
        lab.font = UIFont.systemFont(ofSize: 14)
        lab.textAlignment = .center
        return lab
    }()
    
    var writeCircleV:UIImageView?
    
    var isHiddenLabel: Bool = false{
        
        didSet{
            
            if (isHiddenLabel == true) {
                
                stepButton.isHidden = true;
                
                disAndCalLabel.isHidden = true;
            }else{
                
                
                stepButton.isHidden = false;
                
                disAndCalLabel.isHidden = false;
            }
            
        }
    }
    
    let stepButton:UIButton = {
        
        let btn:UIButton = UIButton(font: 14, textAligent: .center, title: "", titleColor: UIColor(colorLiteralRed: 0/255.0, green: 151/255.0, blue: 219/255.0 , alpha: 1.0))
        
        return btn
    }()
    
    
    
    @objc func drawPro()  {
        
        print(_startRate,_rate, (CGFloat(M_PI)/CGFloat(180.0))*_startAngle,(CGFloat(M_PI)/CGFloat(180.0))*(_startAngle + 3.6));
        if (CGFloat(_startRate) >= CGFloat(_rate)) {
            _displayLink.isPaused = true;
            return;
        }
        _startRate += 1;
        
        _bPath.addArc(withCenter: CGPoint(x: self.width / 2, y:  self.height * 0.5), radius: self.height * 0.35, startAngle: (CGFloat(M_PI)/CGFloat(180.0))*CGFloat(_startAngle), endAngle: (CGFloat(M_PI)/CGFloat(180.0))*CGFloat(_startAngle + 3.6), clockwise: true)
        _shapeLayer.path = _bPath.cgPath;
        _startAngle += 3.6;
        
    }

    override init(frame: CGRect) {
        
        super.init(frame: frame)
      
         self.setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setUpUI()  {
        
        _startAngle = -90
        
        _rWidth = self.height * 0.35
        
        layer.addSublayer(_shapeLayer)
        
        _displayLink = CADisplayLink(target: self, selector: #selector(drawPro))
        
        _displayLink.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
        
        _displayLink.isPaused = true
        
        _startAngle = -90;
        
        _startRate = 0;
        
        
       drawCircle()
        
       drawScale()
       setResult()
        
        self.backgroundColor = UIColor.white
        
    }
    
    
    
    func doViewAnimation()  {
        
        if (_displayLink.isPaused == true) {
        
            _displayLink.isPaused = false;
        }
        
    }

    func degreesToRadians(rod:CGFloat) -> CGFloat {
        
        return (CGFloat(M_PI)*CGFloat(rod))/CGFloat(180.0)
    }
    
    func setResult()  {
        
       stepButton.frame = CGRect(x: (self.width-200)*0.5, y: self.height * 0.5-30, width: 200, height: 30)
        
      addSubview(stepButton)
        
        disAndCalLabel.frame = CGRect(x: (self.width-200)*0.5, y: self.height * 0.5, width: 200, height: 30)
        
      addSubview(disAndCalLabel)
        
      let Rad:CGFloat = (self.circelRadius - self.lineWidth) / 2;
        
     writeCircleV = UIImageView(frame: CGRect(x: self.width / 2, y: self.height/2-Rad-5, width: 10, height: 10))
     writeCircleV?.image = #imageLiteral(resourceName: "mengmengde")
        writeCircleV?.contentMode = .redraw
     addSubview(writeCircleV!)
        
     setInitialLabelAndButton()
        
        
        
    }
    
    func setInitialLabelAndButton()  {
        
        //设置初始值
        disAndCalLabel.text = "0m | 0卡"
        
        disAndCalLabel.textColor = kWatchColor
       
        let str:String = "0步"
        let  AttributedStr:NSMutableAttributedString = NSMutableAttributedString(string: str)
        
        AttributedStr.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 36)], range: NSMakeRange(0, 1))
        
        AttributedStr.addAttributes([NSForegroundColorAttributeName:kWatchColor], range: NSMakeRange(0, 2))
        
        stepButton.setAttributedTitle(AttributedStr, for: .normal)
    }
    
    
    func drawCircle()  {
        
       //画圆
            //圆的直径
            self.circelRadius = self.frame.size.width - 110.0
        self.lineWidth = 2.0;
        let Rad:CGFloat = CGFloat((self.circelRadius - self.lineWidth) / 2);
        
        let tickPath:UIBezierPath = UIBezierPath(arcCenter: CGPoint(x: self.width / 2, y:  self.height * 0.5), radius: Rad, startAngle: CGFloat(degreesToRadians(rod: 0)), endAngle: degreesToRadians(rod: 360), clockwise: true)
        
        
        // 底色
        self.bottomLayer = CAShapeLayer()
        self.bottomLayer?.frame = self.bounds
        self.bottomLayer?.fillColor = UIColor.clear.cgColor
        self.bottomLayer?.strokeColor = UIColor.cz_color(withHex: 0xe8e8e8).cgColor
        self.bottomLayer?.opacity = 0.5
        self.bottomLayer?.lineCap = kCALineCapButt
        self.bottomLayer?.lineWidth = self.lineWidth
        self.bottomLayer?.path = tickPath.cgPath
        self.layer.addSublayer(self.bottomLayer!)
    }

    func drawScale() {

        let perAngle = Float(2*M_PI) / 250
        let calWidth = Float(perAngle) / 4;
        
        for i in 0...249 {
            
            let startAngel = Float(-M_PI) + perAngle*Float(i)
            let endAngel = startAngel + calWidth;
            let tickPath:UIBezierPath = UIBezierPath(arcCenter: self.center, radius: self.height * 0.35, startAngle: CGFloat(startAngel), endAngle: CGFloat(endAngel), clockwise: true)
            let shap:CAShapeLayer = CAShapeLayer()
            shap.strokeColor = UIColor(colorLiteralRed: 99/255.0, green: 200/255.0, blue: 252/255.0, alpha: 1.0).cgColor
            shap.lineWidth = 9
            shap.path = tickPath.cgPath
            self.layer.addSublayer(shap)
            
        }
    }
    
    
    func calculateTextPosition(center:CGPoint,angle:CGFloat) -> CGPoint{
 
        let calRadius:CGFloat = self.circelRadius * 0.5;
        let x:CGFloat = calRadius * CGFloat(cosf(Float(angle)))
        let y:CGFloat = calRadius * CGFloat(sinf(Float(angle)))
        return CGPoint(x: x + center.x, y: -y + center.y)
    
    }
    
    func startAnimation()  {
       
        setInitialLabelAndButton()
        
        isAnimating = false;
        
        timer = Timer(timeInterval: 1, target: self, selector: #selector(self.doCircle), userInfo: nil, repeats: true)
        RunLoop.current.add(timer!, forMode: RunLoopMode.defaultRunLoopMode)
//        timer?.fire()
        
    }
    
    func stopAnimation()  {
        
        let point:CGPoint  = calculateTextPosition(center: CGPoint(x: self.width * 0.5, y: self.height * 0.5), angle: degreesToRadians(rod: 90))
            
        
        writeCircleV?.center = point;
        
        timer?.invalidate()
        
        timer = nil
        
        isAnimating = false
    }
    
    func doCircle()  {
        
         rad += 2
        
        print(rad)
        
        let angel:CGFloat  = degreesToRadians(rod: CGFloat(rad))
        
        let point:CGPoint  = calculateTextPosition(center:CGPoint(x: self.width * 0.5, y: self.height * 0.5) , angle: -angel)
        
//      print(NSStringFromCGPoint(point))
        
        writeCircleV?.transform = (writeCircleV?.transform)!.translatedBy(x: -2.1, y: -2.1)
    
     
        print(NSStringFromCGRect((writeCircleV?.frame)!))
        

    }
    override func draw(_ rect: CGRect) {
        super.draw(rect)
       print(NSStringFromCGRect(rect))
   
       
       // writeCircleV?.frame = CGRect(origin: point, size: CGSize(width: 10, height: 10))
        
        
    }
    deinit {
        
        timer?.invalidate()
        
        timer = nil
    }

}
